package com.frikinet.gestorepub.web.spring.services;

import java.lang.reflect.Field;

import org.springframework.stereotype.Service;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

@Service
public class CacheService
{
	private MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
	
	private <T> String getCacheKey(T object)
	{
		try
		{
			Class<?> clazz = object.getClass();
			Field id = clazz.getDeclaredField("id");
			id.setAccessible(true);
			return getCacheKey(clazz, id.get(object));
		}
		catch(Exception e)
		{
			return null;
		}
	}
	
	private String getCacheKey(Class<?> clazz, Object id)
	{
		return String.format("%s-%s", clazz.getSimpleName(), id);
	}
	
	public <T> void put(T object)
	{
		String key = getCacheKey(object);
		if(key != null)
		{
			cache.put(key, object);
		}
	}
	
	public void put(String key, Object value)
	{
		cache.put(key, value);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T get(Class<T> clazz, Object id)
	{
		String key = getCacheKey(clazz, id);
		if(key != null)
		{
			return (T)cache.get(key);
		}
		return null;
	}
	
	public Object get(String key)
	{
		return cache.get(key);
	}
	
	public <T> void delete(T object)
	{
		String key = getCacheKey(object);
		if(key != null)
		{
			cache.delete(key);
		}
	}
}
